<?php
namespace App\Managers\Admin;

use App\Managers\BaseManager;
use App\Models\AdminGroupModel;
use App\Models\AdminRoleModel;
use App\Models\AdminRoutesModel;
use App\Models\AdminUsersModel;
use App\Util\LoginUtil;
use App\Util\Tree;

class AdminRoutesManager extends BaseManager
{
    public function __construct( AdminRoutesModel $model)
    {
        parent::__construct();
        $this->model = $model;
    }


    public function _before_lists(){
        $routes_id = $this->getData('routes_id','');
        if(!empty($routes_id)){
            $routes_id = is_string($routes_id) ? explode(",", $routes_id) : $routes_id;
            $this->setData('routes_id', $routes_id);
        }
    }


    public function _format($data)
    {
        if (empty($data)) {
            return $data;
        }

        $checkData = [];//存储当前勾选数据

        //组织架构的菜单
        $group_id = $this->getData('group_id');
        if($group_id)
        {
            //获取当前组织架构的所有菜单ID
            $routes_id = AdminGroupModel::query()->where('id',$group_id)->value('routes_id');
            $checkData =  explode(',',$routes_id);
        }

        //角色的菜单
        $role_id = $this->getData('role_id');
        if($role_id){
            //获取当前组织架构的所有菜单ID
            $routes_id = AdminRoleModel::query()->where('id',$role_id)->value('routes_id');
            $checkData =  explode(',',$routes_id);
        }

        $data->transform(function ($item) use ($checkData) {
            $id = data_get($item, 'id');
            $checked = in_array($id, $checkData) ? true : false;                // 是否当前角色/组织已经勾选的数据
            data_set($item,'checked',$checked);

            $menu_id = data_get($item,'menu_id',"");
            $menu_list =  $menu_id ? explode(",", $menu_id) : [];
            data_set($item,'menu_list',$menu_list);
            return $item;
        });


        return$data;

    }



    function _before_save()
    {
        // 权限
        $menu_list = $this->getData('menu_list');
        if(!empty($menu_list)){
            $menu_list = is_array($menu_list) ? implode(',', $menu_list) : $menu_list;
            $this->setData('menu_id', $menu_list);
        }
        $menu_id = $this->getData('menu_id');
        if(!empty($menu_id)){
            $menu_id = is_array($menu_id) ? implode(',', $menu_id) : $menu_id;
            $this->setData('menu_id', $menu_id);
        }
    }

    function _after_delete(){
        /*==== menu删除时删除子菜单 ====*/
        $pk = $this->getModel()->getKeyName();
        if (isset($this->data[$pk]) && !empty($this->data[$pk])) {
            if (strpos($this->data[$pk], ',') !== false) {
                $where = ['pid', 'IN', $this->data[$pk]];
            } else {
                $where['pid'] = $this->data[$pk];
            }
            $this->getModel()->newQuery()->where($where)->delete();
        }
    }

}
